package com.ssm.blog.controller;

import com.github.pagehelper.PageInfo;
import com.ssm.blog.pojo.AdminUser;
import com.ssm.blog.pojo.Role;
import com.ssm.blog.service.AdminUserService;
import com.ssm.blog.service.RoleService;
import com.ssm.blog.util.Constants;
import com.ssm.blog.util.Funcs;
import com.ssm.blog.util.JsonUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.ModelAndView;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Controller
@RequestMapping("/adminuser.html")
public class AdminUserController {
    @Autowired
    private AdminUserService adminUserService;

    @RequestMapping(params = "act=list")
    @ResponseBody
    public Map<String, Object> userList(AdminUser user, Integer page, Integer rows) {
        PageInfo<AdminUser> pageInfo = adminUserService.getAdminUsers(user, page, rows);
        return JsonUtil.getDatagridPagerResult(pageInfo.getTotal(), pageInfo.getList());
    }

    @RequestMapping(params = "act=edit")
    @ResponseBody
    public Map<String, Object> editUser(AdminUser adminUser) throws Exception {
        if (!StringUtils.isEmpty(adminUser.getPassword())) {
            adminUser.setPassword(Funcs.MD5(adminUser.getPassword() + Constants.PASSWORD_SALT_KEY));
        }
        if (adminUser.getId() == null) {
            adminUserService.addAdminUser(adminUser);
        } else {
            adminUserService.updateAdminUser(adminUser);
        }
        return JsonUtil.getSuccessMessage("编辑成功", null);
    }

    @Autowired
    private RoleService roleService;

    //加载所有角色
    @RequestMapping(params = "act=role_list")
    @ResponseBody
    public List<Role> getAllRoles() {
        return roleService.getRoleList(null);
    }

    //加载被编辑的用户角色
    @RequestMapping(params = "act=user_role")
    @ResponseBody
    public List<Integer> getUserRole(Integer userId) {
        List<Integer> ids = roleService.getUserRoleIds(userId);
        return ids;
    }

    @RequestMapping(params = "act=assign_role")
    @ResponseBody
    public Map<String, Object> addUserRole(Integer userId, Integer[] roleIds) throws Exception {
        roleService.addUserRole(userId, roleIds);
        return JsonUtil.getSuccessMessage("授权成功", null);
    }
}
